import express from 'express';
import { Cashgift } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import tbApi from '../../lib/tbapi'; // 淘宝接口API
import CONFIG from '../../../config/config.config'
import baseDao from '../../lib/baseDao'; // 用于获取实例化的sequelize
import { sendMuban, addMoney } from '../../utils/utils'; // 工具类

const router = express.Router();

router.get('/', async function (Request, Response, next) {
  let param = Request.body

  Cashgift.Modal.findAll({
    where: {
      status: 1, // 只有状态为1需要监控
    },
    raw: true, // 返回标准json格式
  }).then(async res => {
    
    for(let i = 0; i < res.length; i++){
      const transaction = await baseDao.sequelize.transaction() // 事务
      await readRecord(res[i], transaction, Response)
    }
    Response.json({
      message: "success"
    });
    
  }).catch(async err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function readRecord(item, transaction, Response) {
  // 读取每一条淘礼金记录
  return new Promise((resolve, reject) => {
    tbApi.index({
      method: 'taobao.tbk.dg.vegas.tlj.instance.report', // 查询淘礼金信息
      rights_id: item.rightsId
    }).then(async res => {
      let result = res.tbk_dg_vegas_tlj_instance_report_response.result
      if(result.success && result.model.unfreeze_amount){ // 查询成功
        let changeStatus = 0 // 修改后的status
        if(Number(result.model.unfreeze_amount) > 0 || Number(result.model.refund_amount) > 0){ // 存在解冻金额或者则返还积分
          let money =  Number(result.model.unfreeze_amount) > 0 ? Number(result.model.unfreeze_amount) : Number(result.model.refund_amount)// 淘礼金退款金额
          console.log('退还金额:' + money)
          changeStatus = 3
          // 加款操作
          let addParam = {
            userId: item.userId,
            title: '淘礼金过期积分返还',
            addGold: money * 10, // 要加的积分
          }
          await addMoney(addParam, transaction, Response).then(res => {
            console.log('增加成功，当前积分：', res)
          })
        } else{ // 已使用
          changeStatus = 2
        }
        Cashgift.Modal.update({
          status: changeStatus, // 1已创建2已使用3已过期
        }, {
            where: {
              id: item.id,
            },
            transaction: transaction
          }).then(async res => {
            await transaction.commit() // 提交事务
            resolve(res)
          }).catch(async err => {
            console.log(err)
            await transaction.rollback() // 回滚
            Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
          });
      }else{
        await transaction.commit() // 提交事务
        resolve('礼金尚未领取或使用，无需处理')
      }
    }).catch(async err => {
      console.log(err)
      await transaction.rollback() // 回滚
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;